const User = require("../modules/User");
//加密
const bcrypt = require("bcrypt");

//实现身份验证和授权的开放标准
const jwt = require("jsonwebtoken");

const { jwt_secret, expiresIn } = require("../config/config");

function getToken(preload = {}) {
  return jwt.sign(preload, jwt_secret, { expiresIn });
}

module.exports = {
  async login(user) {
    const u = {
      _id: "123",
    };
    // const u = await User.findOne({ name: user.name });
    // if (!u) return { code: 0, msg: "用户不存在,请重新输入" };
    // // 比较密码是否一致
    // try {
    //   let flag = await bcrypt.compare(user.password, u.password);
    //   if (!flag) return { code: 0, msg: "密码不正确" };
    // } catch (error) {
    //   return { code: 0, msg: "比较加密密码时执行错误" };
    // }

    //生成token
    const token = getToken({ _id: u._id, name: user.name });
    return { code: 1, data: token };
  },
  async register(user) {
    // const u = await User.findOne({ name: user.name });

    // if (u) {
    //   return { code: 0, msg: `用户名${user.name}已存在` };
    // }
    //create 会返回插入到数据库后的doc对象,也即是会有_id
    // const res = await User.create(user);
    // const token = getToken({ _id: res.id, name: user.name });
    const token = getToken({ _id: 12, name: user.name });
    return { code: 200, data: token };
  },
};
